import {
    HttpRequest,
    HttpHandler,
    HttpEvent, HttpEventType
} from '@angular/common/http';
import { Injectable, Inject, Injector } from '@angular/core';
import { HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { CommService } from 'app/ptpmc/comm/comm.service';
import { LocalStorage } from 'app/ptpmc/localstorage/local.storage';
import { Router, ActivatedRoute } from '@angular/router';
import { Notifycation } from 'app/ptpmc/comm/notifycation';

@Injectable()
export class ResponseInterceptor implements HttpInterceptor {

    constructor(private router: Router) { }

    intercept(req: HttpRequest<any>,
        next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(req).map(event => {

            if (event.type === HttpEventType.DownloadProgress) {
                // console.log('Download progress event', event);
            }
            if (event.type === HttpEventType.UploadProgress) {
                // console.log('Upload progress event', event);
            }
            if (event.type === HttpEventType.Response) {
                // console.log('response received...', event.body);
            }

            if (event instanceof HttpResponse) {
                if (event.body.resultCode === '401') {
                    this.router.navigate(['']);
                    Notifycation.showNotification('身份信息已经过期，请重新登陆', 'info');
                    return;
                } else if (event.body.resultCode === '402') {
                    this.router.navigate(['']);
                    Notifycation.showNotification('身份信息验证失败', 'danger');
                    return;
                }
            }
            return event;
        });
    }
}